<?php
namespace app\platform\middleware;
use app\common\logic\TokenLogic;
use app\common\model\account\AccountModel;
use app\common\model\account\ShopAccountModel;
use app\common\model\AppModel;
use app\common\model\ShopModel;

class Check{
    use \app\BaseTrait;
    /**
     * 处理请求
     *  验证是否登录是否正确的中间件
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        $auth_token = $request->param('auth_token');
        if(empty($auth_token)){
            return $this->error('未登录',100);
        }
        //验证token
        $res = TokenLogic::getShopData($auth_token);
        if(false == $res){
            return $this->error('未登录',100);
        }
        if(empty($res['accountId'])){
            return $this->error('未登录',100);
        }
        if(empty($res['shopId'])){
            return $this->error('未登录',100);
        }

        //验证商户与商铺之间是否存在关系
        if(null === $relation=ShopAccountModel::where([
                ['account_id','=',$res['accountId']],
                ['shop_id','=',$res['shopId']]
            ])->find()){
            return $this->error('您暂未拥有这件商铺',100);
        }
        $request->role_id=$relation->role_id;

        //验证商户
        if(null === $account= AccountModel::find($res['accountId'])){
            return $this->error('账户不存在',100);
        }
        if($account->is_delete != 0){
            return $this->error('账户不存在',100);
        }
        if($account->status != 1){
            return $this->error('账户异常',100);
        }
        $request->accountId=$account->account_id;
        $request->account=$account;

        //验证商铺
        if(null === $shop = ShopModel::find($res['shopId'])){
            return $this->error('商铺不存在',100);
        }
        if($shop->expire_time + 86400 * 7<$request->time()){ //过期后的七天内调用这些接口都可以继续使用，7天过后不能再调用了
            return $this->error('商铺已过期',100);
        }
        $request->shopId=$shop->shop_id;
        $request->shop=$shop;

        //验证应用
        if(null == $app = AppModel::find($shop->app_id)){
            return $this->error('应用不存在',100);
        }

        //开发完成之后再取消注释
//        if($app->status==0){
//            return $this->error('应用还在开发中',100);
//        }
        $request->appId=$app->app_id;
        $request->app = $app;
        $limit=$request->param('limit/d',10);
        $page=$request->param('page/d',1);
        $request->limit=$limit;
        $request->page=$page;

        return $next($request);
    }
}